package br.com.petsis.utilitarios;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.faces.context.FacesContext;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.ServletContext;

public class UtilMail {
	
	public static final String EMAIL_PADRAO_PET = "petsis@petsis.com.br";
	public static final String EMAIL_NOREPLAY = "noreplay@petsis.com.br";
	public static final String SENHA_EMAIL_NOREPLAY = "PetSis2013";
	
	private static final String PROPERTY_USERNAME = "mail.username";
	private static final String PROPERTY_SENHA = "mail.password";
	private static final String PROPERTY_FROM = "mail.from";
	
    /** 
    * Método para Enviar e-mail.
    * @param texto
    * @param destinatario
    * @param assunto
    * @return void
    */
   private static void enviarEmail(String texto, String destinatario, String assunto, Properties p, String caminhoImagens) throws Exception{
	 /*  InputStream input = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/WEB-INF/classes/mail.properties");  
	   Properties p = new Properties();
	   p.load(input);*/
	   //p.put("mail.smtp.host", emailHost);
	   //p.put("mail.smtp.auth", "true");
	   
	   Authenticator auth = new SMTPAuthenticator();
	   Session session = Session.getInstance(p, auth);
	   session.setDebug(true);
	   MimeMessage msg = new MimeMessage(session);
		
	   try {  
		    // "de" e "para"!!  
		    msg.setFrom(new InternetAddress(p.getProperty(PROPERTY_FROM)));  
		    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(destinatario));  
		  
		    msg.setSentDate(new Date());
		  
		    msg.setSubject(assunto);  
		  
		    msg.setText(texto);
		    
		//  
	        // This HTML mail have to 2 part, the BODY and the embedded image  
	        //  
	        MimeMultipart multipart = new MimeMultipart("related");  
	  
	        // first part  (the html)  
	        BodyPart messageBodyPart = new MimeBodyPart();  
	        //String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";  
	        messageBodyPart.setContent(texto, "text/html; charset=UTF-8");  
	  
	        // add it  
	        multipart.addBodyPart(messageBodyPart);  
	          
	        // second part (the image)  
	        messageBodyPart = new MimeBodyPart();
//	        String caminhoImagens = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath("/")+ "img" + java.io.File.separator;;
	        DataSource fds = new FileDataSource  
	          (caminhoImagens+"logo_petsis.jpg");  
	          
	        messageBodyPart.setDataHandler(new DataHandler(fds));  
	        messageBodyPart.setHeader("Content-ID","<image>");  
	  
	        // add it  
	        multipart.addBodyPart(messageBodyPart);  
	  
	        // put everything together  
	        msg.setContent(multipart);  
		  
		    // evniando mensagem (tentando)  
		    Transport.send(msg);  
		}  
		catch (AddressException e) {  
			throw e;
		}  
		catch (MessagingException e) { 
			throw e;
		}  
   }
   
   private static void enviarEmail(String texto, String destinatario, String assunto, byte[] anexo, String nomeAnexo, Properties p, String caminhoImagens ) throws Exception{
	   /*InputStream input = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/WEB-INF/classes/mail.properties");  
	   Properties p = new Properties();
	   p.load(input);*/
	   //p.put("mail.smtp.host", emailHost);
	   //p.put("mail.smtp.auth", "true");
	   
	   Authenticator auth = new SMTPAuthenticator();
	   Session session = Session.getInstance(p, auth);
	   session.setDebug(true);
	   MimeMessage msg = new MimeMessage(session);
	   
	   try {  
		   // "de" e "para"!!  
		   msg.setFrom(new InternetAddress(p.getProperty(PROPERTY_FROM)));  
		   msg.setRecipient(Message.RecipientType.TO, new InternetAddress(destinatario));  
		   
		   msg.setSentDate(new Date());
		   
		   msg.setSubject(assunto);  
		   
		   msg.setText(texto);
		   
		   //  
		   // This HTML mail have to 2 part, the BODY and the embedded image  
		   //  
		   MimeMultipart multipart = new MimeMultipart("related");  
		   
		   // first part  (the html)  
		   BodyPart messageBodyPart = new MimeBodyPart();  
		   //String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";  
		   messageBodyPart.setContent(texto, "text/html; charset=UTF-8");  
		   
		   // add it  
		   multipart.addBodyPart(messageBodyPart);  
		   
		   // second part (the image)  
		   messageBodyPart = new MimeBodyPart();
//		   String caminhoImagens = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath("/")+ "img" + java.io.File.separator;;
		   File file = new File(caminhoImagens+"temp"+java.io.File.separator+nomeAnexo);
		   FileOutputStream fos = new FileOutputStream(file);
		   fos.write(anexo);
		   fos.close();
		   DataSource fds = new FileDataSource(file);  
		   
		   messageBodyPart.setDataHandler(new DataHandler(fds));  
		   messageBodyPart.setHeader("Content-ID","<image>");  
		   
		   // add it  
		   multipart.addBodyPart(messageBodyPart);  
		   
		   // put everything together  
		   msg.setContent(multipart);  
		   
		   // evniando mensagem (tentando)  
		   Transport.send(msg);  
	   }  
	   catch (AddressException e) {  
		   throw e;
	   }  
	   catch (MessagingException e) { 
		   throw e;
	   }  
   }
   
   private static class SMTPAuthenticator extends javax.mail.Authenticator {
       public PasswordAuthentication getPasswordAuthentication() {
//    	   try {
    		  /* InputStream input = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/WEB-INF/classes/mail.properties");
    		   Properties p = new Properties();
    		   p.load(input);*/
//    		   return new PasswordAuthentication(p.getProperty(PROPERTY_USERNAME), p.getProperty(PROPERTY_SENHA));
    		   return new PasswordAuthentication(EMAIL_NOREPLAY, SENHA_EMAIL_NOREPLAY);
    	   /*} catch (IOException e) {
    		   e.printStackTrace();
    		   return null;
    	   }*/
           
       }
   }
   
   public static void enviarEmailAssincrono(String texto, String destinatario, String assunto, byte[] anexo, String nomeAnexo){
	   try {
		   InputStream input = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/WEB-INF/classes/mail.properties");  
		   Properties p = new Properties();
		   p.load(input);
		   
		   String caminhoImagens = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath("/")+ "img" + java.io.File.separator;;
		   
		   ExecutorService executor = Executors.newFixedThreadPool(2);
		   FutureTask<String> future = new FutureTask<String>(new ProcessorEmailTask(texto, destinatario, assunto, anexo, nomeAnexo, p, caminhoImagens));
		   executor.execute(future);
		   executor.shutdown();
		   
	   } catch (IOException e) {
		   // TODO Auto-generated catch block
		   e.printStackTrace();
	   }
	   
   }
   
   public static void enviarEmailAssincrono(String texto, String destinatario, String assunto){
	   try {
		   InputStream input = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/WEB-INF/classes/mail.properties");  
		   Properties p = new Properties();
		   p.load(input);
		   
		   String caminhoImagens = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath("/")+ "img" + java.io.File.separator;;
		   
		   ExecutorService executor = Executors.newFixedThreadPool(2);
		   FutureTask<String> future = new FutureTask<String>(new ProcessorEmailTask(texto, destinatario, assunto, null, null, p, caminhoImagens));
		   executor.execute(future);
		   executor.shutdown();
		   
	   } catch (IOException e) {
		   // TODO Auto-generated catch block
		   e.printStackTrace();
	   }
   }
   
   static class ProcessorEmailTask implements Callable<String>{
	   String texto;
	   String destinatario;
	   String assunto;
	   byte[] anexo;
	   String nomeAnexo;
	   Properties property;
	   String caminhoImagens;
	   
	   public ProcessorEmailTask(String texto, String destinatario,
			   	String assunto, byte[] anexo, String nomeAnexo, Properties property, String caminhoImagens) {
			this.texto = texto;
			this.destinatario = destinatario;
			this.assunto = assunto;
			this.anexo = anexo;
			this.nomeAnexo = nomeAnexo;
			this.property = property;
			this.caminhoImagens = caminhoImagens;
	   }

		@Override
		public String call() throws Exception {
			try{
				if(nomeAnexo == null || nomeAnexo.isEmpty()){
					UtilMail.enviarEmail(texto, destinatario, assunto, property, caminhoImagens);
				}else{
					UtilMail.enviarEmail(texto, destinatario, assunto, anexo, nomeAnexo, property, caminhoImagens);
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
   }
   
}
